const fse = require('fs-extra')
const path = require('path')

const utils = require('./utils/utils.js')
const TemplateParser = require('./parser/templateParser.js')
const CssParser = require('./parser/cssParser.js')
const JsParser = require('./parser/JsParser.js')

const TemplateConverter = require('./converter/templateConverter.js')
const JsConverter = require('./converter/jsConverter.js')
const TemplateBuilder = require('./template/templateBuilder.js')

const cwdPath = path.resolve()
const targetPath = path.join('C:/Users/yunfeng.xu10/Desktop/', 'testminiapp')


//https://juejin.im/post/5c877cd35188257e3b14a1bc

const convert = async function(filepath){
	let fileText = await fse.readFile(filepath, 'utf-8');
	fileHandle(fileText.toString(),filepath)
}

const fileHandle = async function(fileText,filepath){
    const fileName = path.basename(filepath).split('.')[0]
    const convertPath = path.join(path.dirname(filepath),fileName+'.vue')
    let templateConvertedString = ''
    //转换模板开始
    // let templateParser = new TemplateParser();
    // let astTree = await templateParser.parse(fileText)
    // console.log('fmn test templateParser', astTree)
    // // 将微信小程序AST转换为UNIAPP的AST
    // let convertedTemplateAst = TemplateConverter(astTree)
    // // 将AST转换为html文本
    // templateConvertedString += 
    //     `<template>\r\n${templateParser.astToString(convertedTemplateAst)}\r\n\r\n</template>\r\n`
    //转换模板结束
    
    // 转换JS开始
    let jsParser = new JsParser()
    let jsAst = await jsParser.parse(fileText)
    // console.log('fmn test jsAst', JSON.stringify(jsAst));
    // 转换JS结束
    let { convertedJs, vistors } = JsConverter(jsAst)
    let jsCovertedStirng = TemplateBuilder(convertedJs, vistors)
    templateConvertedString =  `<script>\r\n${jsParser.generate(jsCovertedStirng).code}\r\n</script>\r\n`
    let result = await utils.writeFile(convertPath, templateConvertedString)
    console.log('fmn test fileHandle', convertPath, result)


    //转换Css开始
    // let cssParser = new CssParser()
    // let cssAst = cssParser.parse(fileText)
    // let cssCovertedStirng = cssParser.astToString(cssAst)
    //转换Css结束   
    // let result = await utils.writeFile(convertPath, templateConvertedString)

}

console.log('fmn test cwdPath', cwdPath, targetPath);
convert(path.join(targetPath, 'pages/index/index.js'))
